﻿using Quartz.Impl.AdoJobStore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hinacom.Scheduler.Impl
{
    /// <summary>
    /// 对Quartz JobStoreTX 的一些扩展方法，IJobStoreExt的实现
    /// </summary>
    public class JobStoreExtTX : JobStoreTX, IJobStoreExt
    {
        public JobStoreExtTX() : base()
        {
        }

        public JobStoreExtTX(string delegateTypeName, string datasourceName) : base()
        {
            base.delegateTypeName = delegateTypeName;
            base.DataSource = datasourceName;
        }

        public IEnumerable<JobHistory> GetJobHistories(string jobname, string jobgroup, int? lastLoadedId)
        {
            if (!(Delegate is IDriverDelegateExt))
                throw new Exception("The configured driver delegate type does not support the extended methods. A type that implements IDriverDelegateExt is expected.");

            IDriverDelegateExt dxt = (IDriverDelegateExt)Delegate; // 操作实际存储的代理，如SQL Server数据库

            return ExecuteInLock(null, conn =>
            {
                return dxt.GetJobHistories(conn, jobname, jobgroup, lastLoadedId);
            });
        }

        public string GetJobHistoryLog(int historyId)
        {
            if (!(Delegate is IDriverDelegateExt))
                throw new Exception("The configured driver delegate type does not support the extended methods. A type that implements IDriverDelegateExt is expected.");

            IDriverDelegateExt dxt = (IDriverDelegateExt)Delegate; // 操作实际存储的代理，如SQL Server数据库

            return ExecuteInLock(null, conn =>
            {
                return dxt.GetJobHistoryLog(conn, historyId);
            });
        }

        public virtual void SaveJobHistory(JobHistory history)
        {
            if (!(Delegate is IDriverDelegateExt))
                throw new Exception("The configured driver delegate type does not support the extended methods. A type that implements IDriverDelegateExt is expected.");

            IDriverDelegateExt dxt = (IDriverDelegateExt)Delegate; // 操作实际存储的代理，如SQL Server数据库

            ExecuteInLock(null, conn =>
            {
                if (history.Id.HasValue)
                    dxt.UpdateJobHistory(conn, history);
                else
                    dxt.InsertJobHistory(conn, history);
            });
        }
    }
}
